package com.lilong.jwt.common.util;

import com.google.common.collect.Maps;
import com.lilong.jwt.common.exception.ExceptionEnum;
import com.lilong.jwt.common.exception.HydrauException;
import org.springframework.util.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.Map;
import java.util.Set;

public class ValidationUtils {
    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    /**
     * @return ValidationResult
     * @throws
     * @Description: 校验对象属性
     * @author zpp
     * @date 2017年11月28日 上午11:03:16
     * @version 1.0
     */
    public static <T> ValidationResult validateEntity(T obj) {
        ValidationResult result = new ValidationResult();
        Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class);
        if (!CollectionUtils.isEmpty(set)) {
            result.setHasErrors(true);
            Map<String, String> errorMsg = result.getErrorMsg();
            for (ConstraintViolation<T> cv : set) {
                errorMsg.put(cv.getPropertyPath().toString(), cv.getMessage());
            }
            result.setErrorMsg(errorMsg);
        }
        return result;
    }

    /**
     * @return ValidationResult
     * @throws
     * @Description: 按属性校验对象
     * @date 2017年11月28日 上午11:03:36
     * @version 1.0
     */
    public static <T> ValidationResult validateProperty(T obj, String propertyName) throws HydrauException {
        if (null == obj) {
            throw new HydrauException(ExceptionEnum.OBJECT_IS_NULL);
        }
        ValidationResult result = new ValidationResult();
        if (propertyName.indexOf(",") != -1) {
            String[] propertys = propertyName.split(",");
            Map<String, String> errorMsg = Maps.newHashMap();
            for (int i = 0; i < propertys.length; i++) {
                Set<ConstraintViolation<T>> set = validator.validateProperty(obj, propertys[i], Default.class);
                if (!CollectionUtils.isEmpty(set)) {
                    result.setHasErrors(true);
                    for (ConstraintViolation<T> cv : set) {
                        errorMsg.put(propertys[i], cv.getMessage());
                    }
                    result.setErrorMsg(errorMsg);
                }
            }
        } else {
            Set<ConstraintViolation<T>> set = validator.validateProperty(obj, propertyName, Default.class);
            if (!CollectionUtils.isEmpty(set)) {
                result.setHasErrors(true);
                Map<String, String> errorMsg = Maps.newHashMap();
                for (ConstraintViolation<T> cv : set) {
                    errorMsg.put(propertyName, cv.getMessage());
                }
                result.setErrorMsg(errorMsg);
            }
        }
        return result;

    }
}
